<template>
  <div class="file-explorer">
    <el-button @click="selectRootDir">选择照片目录</el-button>
    <span class="checkbox"><el-checkbox v-model="isOnlyContainDoc" label="仅看含文档" size="large" /></span>

    <el-tree :data="fileTree" node-key="path" :props="treeProps" @node-click="debouncedHandleNodeClick"
      :highlight-current="false">
      <template #default="{ node, data }">
        <span class="tree-node">
          <el-icon>
            <component :is="getFileIcon(data)" />
          </el-icon>
          <span>{{ node.label }}</span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import {
  Folder,
  Picture,
  Document,
  Tickets,
  VideoPlay,
} from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'

const fileIcons = {
  directory: Folder,         // 文件夹
  image: Picture,           // 图片
  document: Document,       // Word/文档
  pdf: Tickets,             // PDF
  video: VideoPlay,         // 视频
}
const getFileIcon = (data) => {
  // 如果是目录直接返回文件夹图标
  if (data.type === 'directory') return fileIcons.directory;
  // 如果是文件，根据扩展名返回对应图标
  const extension = data.name.split('.').pop().toLowerCase();
  switch (extension) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
      return fileIcons.image;
    case 'doc':
    case 'docx':
      return fileIcons.document;
    case 'pdf':
      return fileIcons.pdf;
    case 'mp4':
    case 'avi':
    case 'mov':
      return fileIcons.video;
    case 'mp3':
    case 'wav':
      return fileIcons.audio;
    case 'zip':
    case 'rar':
    case '7z':
      return fileIcons.zip;
    default:
      return Document; // 默认文档图标
  }
}
const treeData = ref([])
const emit = defineEmits(['fileSelected'])
const isOnlyContainDoc = ref(false)
const fileTree = computed(() => {
  if (treeData.value.length > 0) {
    return sortTreeData(filterTreeData(treeData.value, isOnlyContainDoc.value));
  } else {
    return []
  }
});

const treeProps = {
  label: 'name',
  children: 'children'
}

const selectRootDir = async () => {
  try {
    const result = await window.electronAPI.selectDirectory()
    if (result) {
      treeData.value = [await window.electronAPI.parseDirectory(result)]
    }
  } catch (error) {
    console.error('目录解析失败:', error)
  }
}

function filterTreeData(treeData, isOnlyContainDoc) {
  return treeData.filter(node => {
    // 如果是文件，直接保留（不在这里筛选 Word 文档）
    if (!node.children) {
      return true;
    }

    // 如果是文件夹，递归处理子节点
    if (node.children && node.children.length > 0) {
      const filteredChildren = filterTreeData(node.children, isOnlyContainDoc);

      // 如果不需要筛选 Word 文档，直接返回所有非空文件夹
      if (!isOnlyContainDoc) {
        if (filteredChildren.length > 0) {
          node.children = filteredChildren;
          return true;
        }
        return false;
      }
      // 如果需要筛选 Word 文档，检查该文件夹是否包含至少一个 Word 文档
      else {
        const hasWordDoc = containsWordDoc(node);
        if (hasWordDoc && filteredChildren.length > 0) {
          node.children = filteredChildren;
          return true;
        }
        return false;
      }
    }

    // 空文件夹不展示
    return false;
  });
}

// 检查当前节点或其子节点是否包含 Word 文档
function containsWordDoc(node) {
  if (!node.children) {
    return node.name.endsWith('.doc') || node.name.endsWith('.docx');
  }
  return node.children.some(child => containsWordDoc(child));
}

const debouncedHandleNodeClick = debounce(async (data) => {
  if (data.type === 'file') {
    const metadata = await window.electronAPI.getImageMetadata(data.path)
    emit('fileSelected', {
      fileTree: fileTree.value,
      path: data.path,
      ...metadata
    })
  }
}, 300)

// 排序树形数据
function sortTreeData(treeData) {
  return treeData.sort((a, b) => {
    // 提取名称前面的数字部分
    const numA = extractLeadingNumber(a.name);
    const numB = extractLeadingNumber(b.name);
    
    // 如果两者都有数字前缀，按数字排序
    if (numA !== null && numB !== null) {
      return numA - numB;
    }
    // 如果只有a有数字前缀，a排在前面
    else if (numA !== null) {
      return -1;
    }
    // 如果只有b有数字前缀，b排在前面
    else if (numB !== null) {
      return 1;
    }
    // 都没有数字前缀，按字母顺序排序
    else {
      return a.name.localeCompare(b.name);
    }
  }).map(node => {
    // 递归排序子节点
    if (node.children) {
      node.children = sortTreeData(node.children);
    }
    return node;
  });
}

// 提取名称前面的数字部分
function extractLeadingNumber(name) {
  const match = name.match(/^(\d+)/);
  return match ? parseInt(match[1], 10) : null;
}
</script>

<style scoped>
.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.checkbox {
  margin-left: 10px;
}
</style>